package com.niodata.dp.expression.function.array;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class IntArrayToStringFunction extends AbstractFunction {

  @Override
  public String getName() {
    return "array.str";
  }

  /**
   * int to string function.
   *
   * @param env env
   * @param array array
   * @return new array
   */
  public AviatorObject call(Map<String, Object> env, AviatorObject array) {
    Object v = array.getValue(env);
    Object[] varray = null;
    if (List.class.isAssignableFrom(v.getClass())) {
      List list = (List) v;
      varray = list.toArray(new Object[list.size()]);
    } else if (v.getClass().isArray()) {
      int len = Array.getLength(v);
      varray = new Object[len];
      for (int i = 0; i < len; i++) {
        varray[i] = Array.get(v, i);
      }
    }
    String[] sarray = new String[varray.length];
    for (int i = 0; i < varray.length; i++) {
      sarray[i] = varray[i] != null ? varray[i].toString() : null;
    }
    Object result = sarray;
    if (List.class.isAssignableFrom(v.getClass())) {
      result = Arrays.asList(result);
    }
    return FunctionUtils.wrapReturn(result);
  }

  /**
   * int to string array.
   *
   * @param env env
   * @param array array
   * @param fmt format
   * @return new array
   */
  public AviatorObject call(Map<String, Object> env, AviatorObject array, AviatorObject fmt) {
    Object v = array.getValue(env);
    Object[] varray = null;
    if (List.class.isAssignableFrom(v.getClass())) {
      List list = (List) v;
      varray = list.toArray(new Object[list.size()]);
    } else if (v.getClass().isArray()) {
      int len = Array.getLength(v);
      varray = new Object[len];
      for (int i = 0; i < len; i++) {
        varray[i] = Array.get(v, i);
      }
    }
    String[] sarray = new String[varray.length];
    String format = FunctionUtils.getStringValue(fmt, env);
    for (int i = 0; i < varray.length; i++) {
      sarray[i] = varray[i] != null ? String.format(format, varray[i]) : null;
    }
    return FunctionUtils.wrapReturn(sarray);
  }
}
